import { NestFactory } from '@nestjs/core';
import { AppModule } from '../../src/app.module';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../../src/users/entities/user.entity';
import { UserRole } from '../../src/common/enums';
import * as argon2 from 'argon2';
import { v4 as uuidv4 } from 'uuid';

async function bootstrap() {
  const app = await NestFactory.createApplicationContext(AppModule);

  try {
    // Get repositories
    const userRepository = app.get<Repository<User>>(getRepositoryToken(User));

    // Check if we already have users
    const userCount = await userRepository.count();
    if (userCount > 0) {
      console.log('Database already has users, skipping seed');
      return;
    }

    // Create admin user
    const adminPassword = await argon2.hash('admin123');
    const adminId = uuidv4();
    const admin = userRepository.create({
      id: adminId,
      username: 'admin@example.com',
      passwordHash: adminPassword,
      role: UserRole.ADMIN,
      displayName: 'System Administrator',
      createdAt: new Date(),
      isActive: true,
    });

    await userRepository.save(admin);
    console.log('Admin user created:', admin.username);
    console.log('Database seeded successfully');
  } catch (error) {
    console.error('Error seeding database:', error);
  } finally {
    await app.close();
  }
}

//bootstrap();
